﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PPAP.Model.Entity;
using PPAP.BO;

namespace PPAP.Web.SearchReport
{
    public partial class SamplingInspection : PageBase
    {
        PPARBO bo = new PPARBO();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                bindDepartment();
                bindData("");
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            bindData("");
        }

        public void bindData(string sort)
        {
            try
            {
                DataTable dt = GetDataSet(sort).Tables[0];
                //dt.Columns.Add("ShowStatus");
                foreach (DataRow r in dt.Rows)
                {
                    r["ShowStatus"] = ShowSampleCardStatus(r["status"].ToString());
                }
                AspNetPager2.RecordCount = dt.Rows.Count;
                dgList.DataSource = GetPageTable(dt, AspNetPager2.PageSize, AspNetPager2.CurrentPageIndex);
                dgList.DataBind();
            }
            catch (Exception ex)
            {
                AlertMessage(ex.Message.ToString());
            }
        }

        private DataSet GetDataSet(string sort)
        {
            PPAP.Model.Search.SamplingInspectionSearch sis = new Model.Search.SamplingInspectionSearch();
            sis.PartNo = this.tbPartno.Text;
            sis.SupplierNo = this.tbSupplierNo.Text;
            if (this.dpStartTime1.Text != "")
                sis.StartTime1 = base.ToDateTime(this.dpStartTime1.Text, "error format!");
            if (this.dpStartTime2.Text != "")
                sis.StartTime2 = base.ToDateTime(this.dpStartTime2.Text, "error format!");
            if (this.dpEndTime1.Text != "")
                sis.EndTime1 = base.ToDateTime(this.dpEndTime1.Text, "error format!");
            if (this.dpEndTime2.Text != "")
                sis.EndTime2 = base.ToDateTime(this.dpEndTime2.Text, "error format!");
            if (this.ddlDept.SelectedValue != "")
                sis.DepartmentID = base.ToInt32(this.ddlDept.SelectedValue, "error format!");
            sis.DeptRep = this.tbDeptRep.Text;
            if (this.ddlStatus.SelectedValue != "")
                sis.Status = base.ToInt32(this.ddlStatus.SelectedValue, "error format!");
            if (this.ddlResult.SelectedValue != "")
                sis.Result = this.ddlResult.SelectedValue;
            sis.pparno = txtPPARNO.Text;
            sis.SupplierName = this.txtSupplierName.Text;
            sis.PartName = this.txtPartName.Text;
            sis.Overdue = RadioButton6.Checked ? "All" : RadioButton3.Checked ? "Yes" : "No";
            sis.MyCase = this.chkMycase.Checked;
            sis.CreateUser = CurrentUser.Id;
            sis.Card = txtSampleCardNo.Text;
            sis.Color = txtColor.Text;
            sis.Finshed = RadioButton5.Checked ? "All" : RadioButton1.Checked ? "Yes" : "No";

            DataSet dt = bo.GetSamplingInspection(sis, sort);
            return dt;
        }

       

        //状态显示
        public string ShowSampleCardStatus(string Status)
        {
            string result = "";
            result = "";

            switch (Status.ToLower())
            {

                case "0":
                    result = "Created";
                    break;
                case "1":
                case "4":
                case "5":
                    result = "Circulating";
                    break;
                case "2":
                    result = "Circulating(<font color='red'>Reject</font>)";
                    break;
                default:
                    result = "Decided";
                    break;
            }
            return result;
        }

        private void bindDepartment()
        {
            TestDepartmentBO tdbo = new TestDepartmentBO();
            DataTable dt = tdbo.GetList("").Tables[0];
            ListItem item;
            item = new ListItem("All", "0");
            this.ddlDept.Items.Add(item);
            foreach (System.Data.DataRow row in dt.Rows)
            {
                item = new ListItem(row["TESTITEMNAME"].ToString(), row["ID"].ToString());
                this.ddlDept.Items.Add(item);
            }
        }

        protected void AspNetPager2_PageChanged(object sender, EventArgs e)
        {
            BindGridView();
        }

        /// <summary>
        /// Export
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                DataSet ds = GetDataSet("");
                //ds.Tables[0].Columns.Add("ShowStatus");
                foreach (DataRow r in ds.Tables[0].Rows)
                {
                    r["ShowStatus"] = ShowSampleCardStatus(r["status"].ToString());
                    r["d1"] = r["starttime"].ToString() == "" ? r["starttime"] : DateTime.Parse(r["starttime"].ToString()).ToString("yyyy-MM-dd");
                    r["d2"] = r["endtimeplan"].ToString() == "" ? r["endtimeplan"] : DateTime.Parse(r["endtimeplan"].ToString()).ToString("yyyy-MM-dd");
                    r["d3"] = r["endtimeactual"].ToString() == "" ? r["endtimeactual"] : DateTime.Parse(r["endtimeactual"].ToString()).ToString("yyyy-MM-dd");
                }
                ds.Tables[0].Columns.Remove("ID");
                ds.Tables[0].Columns.Remove("rid");
                //ds.Tables[0].Columns.Remove("SAMPLECARDNO");
                // ds.Tables[0].Columns.Remove("VERSION");
                //  ds.Tables[0].Columns.Remove("TESTDEPARTMENTID");
                // ds.Tables[0].Columns.Remove("DEPTREP");
                // ds.Tables[0].Columns.Remove("ENDTIMEACTUAL");
                ds.Tables[0].Columns.Remove("STATUS");
                ds.Tables[0].Columns.Remove("starttime");
                ds.Tables[0].Columns.Remove("endtimeplan");
                ds.Tables[0].Columns.Remove("endtimeactual");
                //ds.Tables[0].Columns.Remove("REASON");
                //ds.Tables[0].Columns.Remove("INTERNALCOMMENT");
                // ds.Tables[0].Columns.Remove("INSPECTIONREPORTID");
                ds.Tables[0].Columns["ShowStatus"].ColumnName = "Status";

                ds.Tables[0].Columns["ROWNUM"].ColumnName = "No.";
                ds.Tables[0].Columns["PPARNO"].ColumnName = "PPAR No.";
                ds.Tables[0].Columns["BDNTPARTNO"].ColumnName = "Part No.";
                ds.Tables[0].Columns["SUPPLIERCODE"].ColumnName = "Supplier Code";
                ds.Tables[0].Columns["SAMPLECARDNO"].ColumnName = "Sample card No.";
                ds.Tables[0].Columns["TESTITEMNAME"].ColumnName = "Sample card";
                ds.Tables[0].Columns["RESULT"].ColumnName = "Result";
                ds.Tables[0].Columns["d1"].ColumnName = "Start time";
                ds.Tables[0].Columns["d2"].ColumnName = "End time(planned)";
                ds.Tables[0].Columns["d3"].ColumnName = "End time(actual)";
                ds.Tables[0].Columns["bdntpartname"].ColumnName = "Part name";
                ds.Tables[0].Columns["qeuser"].ColumnName = "Sample card started by";
                ds.Tables[0].Columns["COLOR"].ColumnName = "Color";
                ds.Tables[0].Columns["DeptRep"].ColumnName = "Responsible person";
                //ds.Tables[0].Columns["testitemname"].ColumnName = "Sample card";
                CreateExcel(ds, "SamplingInspection");
            }
            catch (Exception ex)
            {
                AlertMessage(ex.Message.ToString());
            }
        }

        protected void dgList_SortCommand(object source, DataGridSortCommandEventArgs e)
        {
            // 从事件参数获取排序数据列
            string sortExpression = e.SortExpression.ToString();

            // 假定为排序方向为“顺序”
            string sortDirection = "ASC";
            // “ASC”与事件参数获取到的排序方向进行比较，进行GridView排序方向参数的修改
            if (sortExpression == this.dgList.Attributes["SortExpression"])
            {
                //获得下一次的排序状态
                sortDirection = (this.dgList.Attributes["SortDirection"].ToString() == sortDirection ? "DESC" : "ASC");
            }
            // 重新设定GridView排序数据列及排序方向
            this.dgList.Attributes["SortExpression"] = sortExpression;
            this.dgList.Attributes["SortDirection"] = sortDirection;


            string pic = "";
            pic = sortDirection == "ASC" ? "<img src='../Images/icon/arrowup.gif' />" : "<img src='../Images/icon/arrowdown.gif' />";

            foreach (DataGridColumn item in dgList.Columns)
            {
                if (item.SortExpression == sortExpression)
                {
                    item.HeaderText = item.FooterText + " " + pic;
                }
                else
                    item.HeaderText = item.FooterText;
            }

            this.BindGridView();

        }

        private void BindGridView()
        {
            // 获取GridView排序数据列及排序方向
            string sortExpression = this.dgList.Attributes["SortExpression"];
            string sortDirection = this.dgList.Attributes["SortDirection"];
            if (sortExpression != null)
            {
                // 调用业务数据获取方法
                string sort = string.Format("  order by lower({0})  {1} ", sortExpression, sortDirection);
                if (sortExpression == "starttime" || sortExpression == "endtimeplan" || sortExpression == "endtimeactual")
                {
                    sort = string.Format("  order by {0}  {1} ", sortExpression, sortDirection);
                }
                DataTable dtBind = GetDataSet(sort).Tables[0];
                foreach (DataRow r in dtBind.Rows)
                {
                    r["ShowStatus"] = ShowSampleCardStatus(r["status"].ToString());
                }
                // 根据GridView排序数据列及排序方向设置显示的默认数据视图
                if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
                {
                    dtBind.DefaultView.Sort = string.Format("{0} {1}", sortExpression, sortDirection);
                }
                // GridView绑定并显示数据
                this.dgList.DataSource = GetPageTable(dtBind, AspNetPager2.PageSize, AspNetPager2.CurrentPageIndex);
                this.dgList.DataBind();
            }else
                btnSubmit_Click(null, null);
        }
    }
}